package controllers

import java.io.File
import java.text.SimpleDateFormat
import java.util.Date

import akka.stream.IOResult
import akka.stream.scaladsl.{FileIO, Sink}
import akka.util.ByteString
import dao._
import javax.inject.Inject
import models.Tables.RecordRow
import org.apache.commons.io.FileUtils
import org.joda.time.DateTime
import play.api.libs.json.Json
import play.api.libs.streams.Accumulator
import play.api.libs.ws.WSClient
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc._
import play.core.parsers.Multipart.{FileInfo, FilePartHandler}
import shared._
import tool.{DesEncrypter, FormTool, Tool}
import utils.Utils

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
  * Created by yz on 2018/8/20
  */
class AdminController @Inject()(cc: ControllerComponents, formTool: FormTool, ws: WSClient, tool: Tool,
                                accountDao: AccountDao, recordDao: RecordDao) extends AbstractController(cc) {

  def manageBefore = Action { implicit request =>
    Ok(views.html.admin.manage())
  }

  def logout = Action { implicit request =>
    Redirect(routes.AppController.loginBefore()).flashing("info" -> "退出登录成功!", "class" -> Utils.successClass).
      removingFromSession(Shared.adminStr)
  }

  def getAllFile = Action { implicit request =>
    getAllFileAction(request)
  }

  def getAllFileAction(request: RequestHeader): Result = {
    val array = Utils.dataDir.listFiles().map { file =>
      val df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
      val timeStr = df.format(new Date(file.lastModified()))
      val address = s"http://${request.host}${routes.AppController.download()}?fileName=${file.getName}"
      Json.obj("name" -> file.getName, "time" -> timeStr, "address" -> address)
    }
    Ok(Json.toJson(array))
  }

  def changePasswordBefore = Action { implicit request =>
    Ok(views.html.admin.changePassword())

  }

  def changePassword = Action.async { implicit request =>
    val data = formTool.changePasswordForm.bindFromRequest().get
    accountDao.selectById1.flatMap { x =>
      if (data.password == x.password) {
        accountDao.updatePassword(data.newPassword).map { y =>
          Redirect(routes.AppController.loginBefore()).flashing("info" -> "密码修改成功!", "class" -> Utils.successClass).
            removingFromSession(Shared.adminStr)
        }
      } else {
        Future.successful(Redirect(routes.AdminController.changePasswordBefore()).flashing("info" -> "旧密码错误!", "class" -> Utils.errorClass))
      }
    }
  }

  def uploadFile = Action(parse.multipartFormData) { implicit request =>
    val tmpDir = tool.createTempDirectory("tmpDir")
    request.body.files.filter(_.key == "dataFile").foreach { tmpFile =>
      if (tmpFile.ref.path.toFile.length() > 0) {
        val file = new File(Utils.dataDir, tmpFile.filename)
        tmpFile.ref.moveTo(file, replace = true)
      }
    }
    getAllFileAction(request)

  }

  def deleteFile = Action { implicit request =>
    val data = formTool.fileNameForm.bindFromRequest().get
    val file = new File(Utils.dataDir, data.fileName)
    FileUtils.deleteQuietly(file)
    getAllFileAction(request)
  }


}
